package qc.module.platform.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qc.common.core.enums.ResourceStatusFlagEnum;
import qc.common.core.exception.QCPromptException;
import qc.common.core.unify.QCUnifyReturnValue;
import qc.module.platform.dto.phone.OfficialPhoneConditionDto;
import qc.module.platform.dto.phone.OfficialPhoneDto;
import qc.module.platform.dto.phone.SetCategoryIdConditionDto;
import qc.module.platform.entity.QcOfficialCategory;
import qc.module.platform.entity.QcOfficialPhone;
import qc.module.platform.mapper.QcOfficialPhoneMapper;
import qc.module.platform.repository.QcOfficialCategoryRepository;
import qc.module.platform.repository.QcOfficialPhoneRepository;

import java.util.List;

/**
 * @projectName: qcdp
 * @package: qc.module.platform.service
 * @className: OfficialPhoneService
 * @version: 1.0
 */

@Service
public class OfficialPhoneService {


    private QcOfficialPhoneRepository repository;


    @Autowired
    public void setQcOfficialPhoneRepository(QcOfficialPhoneRepository repository) {
        this.repository = repository;
    }

    private QcOfficialCategoryRepository qcOfficialCategoryRepository;


    @Autowired
    public void setQcOfficialCategoryRepository(QcOfficialCategoryRepository qcOfficialCategoryRepository) {
        this.qcOfficialCategoryRepository = qcOfficialCategoryRepository;
    }


    /**
     * 新增号码信息
     *
     * @param dto: 新增电话信息
     * @return String 添加成功返回null,失败返回错误信息
     * @author QcCheng Tech
     * @date 2023/10/7
     */
    public String add(OfficialPhoneDto dto) {
        if (dto == null)
            return QCUnifyReturnValue.Warn("新增电话信息不能为空");
        if (StringUtils.isBlank(dto.getName()))
            return QCUnifyReturnValue.Warn("号码名称不能为空");
        if (StringUtils.isBlank(dto.getPhone()))
            return QCUnifyReturnValue.Warn("号码不能为空");
        if (hasNameExist(dto.getName(), 0x0))
            return QCUnifyReturnValue.Warn("名称已存在!");
        //判断新增时是否选择分类
        //判断选择的分类是否存在
        if (dto.getCategoryId() > 0) {
            if (!hasCategoryExist(dto.getCategoryId()))
                return QCUnifyReturnValue.Warn("号码分类不存在");
        }
        QcOfficialPhone qcOfficialPhone = QcOfficialPhoneMapper.MAPPER.OfficialPhoneDtoToEntity(dto);
        //为新增号码设置ID
        qcOfficialPhone.setId(genereateId());
        //添加信息
        if (repository.insert(qcOfficialPhone) < 0x1)
            return QCUnifyReturnValue.Warn("新增信息失败");
        return QCUnifyReturnValue.Success();
    }


    /**
     * 修改号码信息
     *
     * @param dto:修改信息
     * @return String 成功返回null，失败返回错误信息
     * @author QcCheng Tech
     * @date 2023/10/7
     */
    public String update(OfficialPhoneDto dto) {
        if (dto == null)
            return QCUnifyReturnValue.Warn("修改号码信息不能为空");
        if (StringUtils.isBlank(dto.getName()))
            return QCUnifyReturnValue.Warn("号码名称不能为空");
        //判断指定修改对象是否存在
        if (!hasIdExist(dto.getId()))
            return QCUnifyReturnValue.Warn("修改的手机号对象不存在");
        if (StringUtils.isBlank(dto.getPhone()))
            return QCUnifyReturnValue.Warn("手机号信息不能为空");
        if (hasNameExist(dto.getName(), dto.getId()))
            return QCUnifyReturnValue.Warn("号码名称已存在!");
        //判断选择的分类是否存在
        if (dto.getCategoryId() > 0) {
            if (!hasCategoryExist(dto.getCategoryId()))
                return QCUnifyReturnValue.Warn("号码分类不存在");
        }
        QcOfficialPhone qcOfficialPhone = QcOfficialPhoneMapper.MAPPER.OfficialPhoneDtoToEntity(dto);
        if (repository.updateById(qcOfficialPhone) < 0x1)
            return QCUnifyReturnValue.Warn("修改号码信息失败");
        return QCUnifyReturnValue.Success();
    }

    /**
     * 按id删除指定公务电话
     *
     * @param id:            公务电话id
     * @param isLogicDelete: 是否为逻辑删除，true为逻辑删除
     * @return String
     * @author QcCheng Tech
     * @date 2023/10/7
     */
    public String delete(int id, boolean isLogicDelete) throws QCPromptException {
        if (id < 1)
            throw new QCPromptException("电话号码id不能为空");
        //判断是否为逻辑删除
        if (isLogicDelete) {
            LambdaUpdateWrapper<QcOfficialPhone> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(QcOfficialPhone::getId, id);
            wrapper.set(QcOfficialPhone::getFlag, ResourceStatusFlagEnum.DELETED);
            if (repository.update(null, wrapper) < 0x1)
                return QCUnifyReturnValue.Warn("删除失败");
        } else {
            if (repository.deleteById(id) < 0x1)
                return QCUnifyReturnValue.Warn("删除失败");
        }
        return QCUnifyReturnValue.Success();
    }

    /**
     * 设置号码分类
     *
     * @param condition: 分类信息
     * @return String 成功返回null
     * @author QcCheng Tech
     * @date 2023/10/7
     */
    public String setCategory(SetCategoryIdConditionDto condition) {
        List<Integer> ids = condition.getIds();
        LambdaUpdateWrapper<QcOfficialPhone> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(QcOfficialPhone::getId, ids)
                .set(QcOfficialPhone::getCategoryId, condition.getCategoryId());
        repository.update(null, wrapper);
        return QCUnifyReturnValue.Success();
    }

    /**
     * 按号码id查询手机号信息
     *
     * @param id: 手机号id
     * @return OfficialPhoneDto 查询信息
     * @author QcCheng Tech
     * @date 2023/10/7
     */
    public OfficialPhoneDto get(int id) throws QCPromptException {
        if (id < 1)
            throw new QCPromptException("号码id不能为空");
        QcOfficialPhone qcOfficialPhone = repository.selectById(id);
        if (qcOfficialPhone != null) {
            return QcOfficialPhoneMapper.MAPPER.toDto(qcOfficialPhone);
        }
        return null;
    }


    /**
     * 按条件查询号码
     *
     * @param condition:查询条件 可以为名称，手机号
     * @return List<OfficialPhoneDto> 返回结果集
     * @author QcCheng Tech
     * @date 2023/10/7
     */
    public List<OfficialPhoneDto> query(OfficialPhoneConditionDto condition) {
        LambdaQueryWrapper<QcOfficialPhone> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(condition.getCategoryId())) {
            wrapper.eq(QcOfficialPhone::getCategoryId, condition.getCategoryId());
        }
        if (StringUtils.isNotBlank(condition.getKeywords())) {
            wrapper.and(q ->
                    q.like(QcOfficialPhone::getPhone, condition.getKeywords())
                            .or()
                            .like(QcOfficialPhone::getName, condition.getKeywords())
            );
        }
        //先按排序号进行排序，再按姓名进行排序
        wrapper.orderByAsc(QcOfficialPhone::getOdr, QcOfficialPhone::getName);
        List<QcOfficialPhone> qcOfficialPhones = repository.selectList(wrapper);
        if (!qcOfficialPhones.isEmpty()) {
            return QcOfficialPhoneMapper.MAPPER.toDtoList(qcOfficialPhones);
        }
        return null;

    }

    /**
     * 判断指定号码分类下是否存在手机号信息
     *
     * @param categoryId: 手机号分类ID
     * @return Boolean 判断是否存在手机号信息，存在返回true
     * @author QcCheng Tech
     * @date 2023/10/7
     */
    boolean isCategoryHasPhones(int categoryId) {
        LambdaQueryWrapper<QcOfficialPhone> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(QcOfficialPhone::getId);
        wrapper.eq(QcOfficialPhone::getCategoryId, categoryId);
        QcOfficialPhone en = repository.selectOne(wrapper);
        if (en != null)
            return true;
        return false;
    }


    /**
     * 生成记录ID，获取数据库表中的最大记录ID+1
     *
     * @return 生成记录ID
     * @author QuCheng Tech
     * @since 2023/5/28
     */
    Integer genereateId() {
        Integer maxRecordId = getMaxId();
        return maxRecordId + 1;
    }

    /**
     * 获取数据库表中的最大ID值，没有记录时返回0
     *
     * @return 返回数据库表中的最大ID值
     * @author QuCheng Tech
     * @since 2023/5/28
     */
    Integer getMaxId() {
        LambdaQueryWrapper<QcOfficialPhone> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(QcOfficialPhone::getId);
        wrapper.orderByDesc(QcOfficialPhone::getId);
        QcOfficialPhone en = repository.selectOne(wrapper);
        if (en != null)
            return en.getId();
        return 0x0;
    }

    /**
     * 判断数据库中指定手机号信息是否存在
     *
     * @param id: 手机号ID
     * @return boolean 存在返回true,不存在返回false
     * @author QcCheng Tech
     * @date 2023/10/11
     */
    boolean hasIdExist(int id) {
        LambdaQueryWrapper<QcOfficialPhone> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(QcOfficialPhone::getId);
        wrapper.eq(QcOfficialPhone::getId, id);

        QcOfficialPhone qcOfficialPhone = repository.selectOne(wrapper);
        if (qcOfficialPhone != null)
            return true;
        return false;

    }


    /**
     * 判断名称是否存在，存在返回true
     *
     * @param name: 判断名称
     * @return Boolean 判断名称是否存在，存在返回true
     * @author QcCheng Tech
     * @date 2023/9/28
     */
    boolean hasNameExist(String name, int id) {
        LambdaQueryWrapper<QcOfficialPhone> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(QcOfficialPhone::getId);
        wrapper.eq(QcOfficialPhone::getName, name);
        wrapper.ne(QcOfficialPhone::getId, id);

        QcOfficialPhone qcOfficialPhone = repository.selectOne(wrapper);
        if (qcOfficialPhone != null)
            return true;
        return false;
    }

    /**
     * 判断号码分类信息是否存在，存在返回true
     *
     * @param categoryId: 号码分类ID
     * @return boolean 存在返回true
     * @author QcCheng Tech
     * @date 2023/10/8
     */
    boolean hasCategoryExist(int categoryId) {
        LambdaQueryWrapper<QcOfficialCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(QcOfficialCategory::getId);
        wrapper.eq(QcOfficialCategory::getId, categoryId);
        QcOfficialCategory en = qcOfficialCategoryRepository.selectOne(wrapper);
        if (en != null) {
            return true;
        }
        return false;
    }

}
